package sort

import (
	"bytes"
	"sort"
	"strings"
)

// map key排序，由小到大排序
func MapSort(paramMap map[string]string) []string {
	keys := []string{}
	for key := range paramMap {
		keys = append(keys, key)
	}
	sort.Strings(keys)
	return keys
}

/**
 * 把数组所有元素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
 * @param paramMap 需要排序并参与字符拼接的参数组
 * @return string 拼接后字符串
 */
func CreateLinkStr(paramMap map[string]string) string {
	var stringBuilder bytes.Buffer
	keys := MapSort(paramMap)
	for _, key := range keys {
		value := paramMap[key]
		if strings.Trim(key, " ") != "" {
			if len(stringBuilder.String()) > 0 {
				stringBuilder.WriteString("&")
			}
			stringBuilder.WriteString(key + "=" + value)
		}
	}
	return stringBuilder.String()
}
